package com.lining.orangeservice.controller;

import cn.hutool.json.JSONObject;
import com.lining.orangeservice.common.Result;
import com.lining.orangeservice.entity.dto.request.CaptchaRequest;
import com.lining.orangeservice.service.CaptchaService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/captcha")
@Tag(name = "验证码接口", description = "生成验证码和验证验证码")
public class CaptchaController {

    @Autowired
    private CaptchaService captchaService;

    /**
     * 获取验证码
     */
    @GetMapping("/get")
    @Operation(summary = "获取验证码")
    public ResponseEntity<JSONObject> getCaptcha(HttpServletRequest request) {
        JSONObject captchaInfo = captchaService.generateCaptcha();
        // 将验证码存储在session中
        HttpSession session = request.getSession();
        session.setAttribute("captcha_code", captchaInfo.getStr("code"));
        return ResponseEntity.ok(captchaInfo);
    }

    /**
     * 验证验证码
     */
    @Operation(summary = "验证验证码")
    @PostMapping("/validate")
    public ResponseEntity<Result<Void>> validateCaptcha(@RequestBody CaptchaRequest request, 
                                                       HttpServletRequest httpRequest) {
        String code = request.getCode();
        HttpSession session = httpRequest.getSession();
        String sessionCode = (String) session.getAttribute("captcha_code");
        
        if (captchaService.validateCaptcha(code, sessionCode)) {
            session.removeAttribute("captcha_code");
            return ResponseEntity.ok(Result.success());
        } else {
            return ResponseEntity.ok(Result.error(400, "验证码错误"));
        }
    }
}